import Vue from 'vue';
import VueRouter from 'vue-router';
import Home from '@/views/Home.vue';
import {
  getToken
} from '@/utils/token-util';
import {
  getUserInfo
} from '@/api/index';
Vue.use(VueRouter);
/**
 * @属性说明
 * redirect 路由重定向属性
 * @p {index}  区分父页面和子页面
 * @p 0 父页面
 * @p 1 子界面
 * */
const routes = [{
    path: '/',
    name: '首页',
    component: Home,
    meta: {
      index: 0,
      show: true,
    },
  },
  {
    path: '/loagin',
    name: '登陆',
    meta: {
      show: false,
    },
    component: () => import('../components/loagin.vue'),
  },
  {
    path: '/classification',
    name: '分类',
    meta: {
      show: true,
    },
    component: () => import('../components/Home/Classification.vue'),
  },
  {
    path: '/form',
    name: '表单',
    meta: {
      show: true,
    },
    component: () => import('../components/Home/Form.vue'),
  },
  {
    path: '/personalCenter',
    name: '我的',
    meta: {
      show: true,
    },
    component: () => import('../components/Home/PersonalCenter.vue'),
  },
  {
    path: '/specialeffects/home',
    name: '动画类',
    meta: {
      index: 1,
      show: true,
    },
    component: () => import('../components/SpecialEffects/Home.vue'),
  },
  {
    path: '/ceshi',
    name: '数组测试',
    meta: {
      show: true,
    },
    component: () => import('../views/test/ceshi.vue'),
  },
  {
    path: '*',
    name: '404',
    meta: {
      show: false,
    },
    component: () => import('../views/exception/404.vue'),
  },
];

const router = new VueRouter({
  routes,
});

/**
 * @这里是登录逻辑的拦截器如果没有的话可以拿掉判断直接next方法就可以了
 * */
router.beforeEach((to, from, next) => {
  document.title = '模板项目' + ' | ' + to.name;
  // 判断是否需要登陆
  if (to.meta.show) {
    if (!getToken()) {
      next({
        path: '/loagin',
        query: to.path === '/' ? {} : {
          from: to.path
        }
      });
    } else {
      // getUserInfo();
      next();
      return;
    }
  } else {
    if (to.name === '登陆') {
      if (getToken()) {
        next('/');
      } else {
        getUserInfo();
        next();
      }
      return;
    } else {
      if (to.name == 404) {
        next();
        return;
      } else {
        next('/');
      }
    }
  }
});

// 微信登陆(需要就释放)
// router.beforeEach(function (to, from, next) {
//   document.title = to.meta.name;
//   let token = localStorage.getItem('token');
//   if (token) {
//     next();
//     return;
//   } else {
//     let query = to.query.token;
//     if (query) {
//       localStorage.setItem('token', base64_decode(query));
//       next();
//     } else {
//       let out = base64encode(window.location.href);
//       let url = `http://api.diandi.jlwl100.com/?s=App.Weixin.Login&url=${out}`;
//       location.href = url;
//     }
//   }
//   // next();
// });
export default router;